package com.example.demo.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.common.DouyinConfig;
import com.example.demo.service.DouyinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class DouyinServiceImpl implements DouyinService {
    @Autowired
    DouyinConfig douyinConfig;
    @Override
    public Map jscode2session(String code) {
        //构建body
        //发送请求
        Map<String, Object> body=new HashMap<>();
        body.put("appid", douyinConfig.getAppId());
        body.put("secret", douyinConfig.getSecret());
        body.put("code", code);
        String bodyStr = JSONUtil.toJsonStr(body);
        String resultStr = HttpUtil.post(douyinConfig.getUrl(), bodyStr);
        System.out.println(resultStr);

        JSONObject jsonObject = JSONUtil.parseObj(resultStr);
        Long resultCode = Long.parseLong(jsonObject.get("err_no").toString());
        String msg=jsonObject.getStr("err_tips");
        if(resultCode==0){
            return jsonObject.get("data", Map.class);
        }
        throw new RuntimeException(msg);

    }
}
